import os
import socket
import json
from datetime import datetime
# TCP连接创建的是双向通道，双方都可以同时给对方发数据。但是谁先发谁后发，怎么协调，要根据具体的协议来决定
# HTTP协议规定客户端必须先发请求给服务器，服务器收到后才发数据给客户端。


def send_msg(resp_dict: dict) -> int:
    # 创建一个client socket:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ip = '127.0.0.1'
    # 建立连接:
    client.connect((ip, 5700))

    msg_type = resp_dict['msg_type']  # 回复类型（群聊/私聊）
    number = resp_dict['number']  # 回复账号（群号/好友号）
    msg = resp_dict['msg']  # 要回复的消息

    # 将字符中的特殊字符进行url编码
    msg = msg.replace(" ", "%20")
    msg = msg.replace("\n", "%0a")

    if msg_type == 'group':
        payload = "GET /send_group_msg?group_id=" + str(
            number) + "&message=" + msg + " HTTP/1.1\r\nHost:" + ip + ":5700\r\nConnection: close\r\n\r\n"
    elif msg_type == 'private':
        payload = "GET /send_private_msg?user_id=" + str(
            number) + "&message=" + msg + " HTTP/1.1\r\nHost:" + ip + ":5700\r\nConnection: close\r\n\r\n"
    print("发送" + payload)
    # 发送数据:
    client.send(payload.encode("utf-8"))
    client.close()
    return 0




def request_to_json(msg):
    for i in range(len(msg)):
        if msg[i] == "{" and msg[-1] == "\n":
            return json.loads(msg[i:])
    return None


def rev_msg():  # json or None
    # 创建监听socket
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.bind(('127.0.0.1', 5701))
    listen_socket.listen(100)  # 等待连接的最大数量
    header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'

    client, address = listen_socket.accept()
    rec = client.recv(1024).decode(encoding='utf-8')
    rev_json = request_to_json(rec)
    client.sendall((header).encode(encoding='utf-8'))
    client.close()
    return rev_json


def main():
    while True:
        now = datetime.now()
        
        print(now.hour,now.minute)
        break

def start():
    os.system('cd D:\\ZIPS\\go-cqhttp_windows_amd64')
    os.system('go-cqhttp.exe')
start()
# main()
# D:\ZIPS\go-cqhttp_windows_amd64\go-cqhttp.exe
# cd D:\ZIPS\go-cqhttp_windows_amd64\
# .\go-cqhttp.exe